package ua.com.fesvlast.hotel.model.commands;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ua.com.fesvlast.hotel.controller.managers.ConfigurationManager;
import ua.com.fesvlast.hotel.model.utils.MailSender;
import ua.com.fesvlast.hotel.model.utils.Validator;

public class SendMessageCommand implements ICommand {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String page=null;
		String erorMessage=null;
		
		String subject=request.getParameter("subject");
		String email=request.getParameter("email").trim();
		String message=request.getParameter("message");
		String name=request.getParameter("name");
		
		if(subject==null || subject.equals("")){
			erorMessage="The subject is empty!";
		}
		if(!Validator.validateEmail(email)){
			erorMessage=Validator.getMessage();
		}
		
		if(message==null || message.equalsIgnoreCase("")){
			erorMessage="Message is empty!";
		}
		
		if(name==null || name.equalsIgnoreCase("")){
			erorMessage="Name is empty!";
		}
		
		if(erorMessage==null){
			boolean flag=MailSender.sendMessage(email, subject, message, name);
			if(flag){
				erorMessage="The mail was successfully delivered!";
				request.setAttribute("errorMessage", erorMessage);
				page=ConfigurationManager.getInstance().getProperty(ConfigurationManager.CONTACT_PAGE);
			}	
		}else{
			request.setAttribute("errorMessage", erorMessage);
			page=ConfigurationManager.getInstance().getProperty(ConfigurationManager.CONTACT_PAGE);
		}
		
		return page;
	}

}
